var button = document.getElementById("login");
var input = document.querySelector("#input");
var video1 = document.getElementById("video1");
var video2 = document.getElementById("video2");
var ul = document.querySelector("ul");
var socket = new WebSocket("ws://192.168.13.203:8001");//192.168.13.203为作为服务器的那台电脑的IP4地址  (win+r  输入cmd打开控制台,输入ipconfig查看IP4地址)
var myname = "";

const configuration = {
    iceServers: [
        {
            urls: "stun:stun.l.google.com:19302"
        }
    ]
};

var pcA;
var pcB;

// 建立连接
socket.addEventListener("open", function () {
    console.log("连接成功!");
});

// 向服务器发送个人数据
button.addEventListener("click", function () {
    myname = input.value;
    socket.send(JSON.stringify({ "type": "add", "name": myname }));
});
// 接收服务器端发的数据
socket.addEventListener("message", async function (data) {
    const msg = JSON.parse(data.data);
    if (msg.type === "users") {
        // 更新用户列表
        let lists = msg.users.filter(item => item !== myname);
        ul.innerHTML = "";
        lists.forEach(item => {
            const li = document.createElement("li");
            li.textContent = item;
            ul.appendChild(li);
        });
        
        document.querySelectorAll("li").forEach(item => {
            item.addEventListener("click", async () => {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({
                        video: true, 
                        audio: true
                    });
                    video1.srcObject = stream; // 显示本地视频
                    pcA = new RTCPeerConnection(configuration);
                    stream.getTracks().forEach(track => {
                        pcA.addTrack(track, stream);
                    });

                    // ICE候选处理
                    pcA.onicecandidate = ({ candidate }) => {
                        if (candidate) {
                            socket.send(JSON.stringify({
                                type: "iceCandidate",
                                send: myname,
                                receive: item.textContent,
                                candidate
                            }));
                        }
                    };

                    // 远程流处理
                    pcA.ontrack = ({ streams }) => {
                        video2.srcObject = streams[0]; // 显示远程视频
                    };

                    // 创建offer
                    const offer = await pcA.createOffer();
                    await pcA.setLocalDescription(offer);
                    
                    socket.send(JSON.stringify({
                        type: "offer",
                        send: myname,
                        receive: item.textContent,
                        offer
                    }));
                } catch (err) {
                    console.error("获取媒体失败:", err);
                }
            });
        });
    } 
    else if (msg.type === "offer") {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ 
                video: true, 
                audio: true 
            });
            video2.srcObject = stream; // 显示本地视频
            
            pcB = new RTCPeerConnection(configuration);
            stream.getTracks().forEach(track => {
                pcB.addTrack(track, stream);
            });

            // ICE候选处理
            pcB.onicecandidate = ({ candidate }) => {
                if (candidate) {
                    socket.send(JSON.stringify({
                        type: "iceCandidate",
                        send: myname,
                        receive: msg.send,
                        candidate
                    }));
                }
            };

            // 远程流处理
            pcB.ontrack = ({ streams }) => {
                video1.srcObject = streams[0]; // 显示远程视频
            };

            // 处理offer并创建answer
            await pcB.setRemoteDescription(msg.offer);
            const answer = await pcB.createAnswer();
            await pcB.setLocalDescription(answer);
            
            socket.send(JSON.stringify({
                type: "answer",
                send: myname,
                receive: msg.send,
                answer
            }));
        } catch (err) {
            console.error("处理offer失败:", err);
        }
    } 
    else if (msg.type === "answer") {
        // 处理answer
        await pcA.setRemoteDescription(msg.answer);
    } 
    else if (msg.type === "iceCandidate") {
        // 添加ICE候选
        const candidate = new RTCIceCandidate(msg.candidate);
        if (pcA && msg.send !== myname) {
            await pcA.addIceCandidate(candidate);
        } else if (pcB) {
            await pcB.addIceCandidate(candidate);
        }
    }
});

// 关闭连接
socket.addEventListener("close", function () {
    socket.send(JSON.stringify({ "type": "del", "name": myname }));
});